﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using Api.Model;


namespace RssProxyService
{
    public class RssMapper : AbstractRssMapper
    {
        public override Article MapSingleArticle(SyndicationItem syndicationItem)
        {
            var article = new Article();
            article.Tags = new[] { new Tag() { Name = "Rss" }, new Tag() { Name = "Adult" } };

            if (syndicationItem.Title != null)
            {
                article.Title = syndicationItem.Title.Text;
            }

            if (syndicationItem.PublishDate.DateTime != new DateTime())
            {
                article.PublishDate = syndicationItem.PublishDate.DateTime;
            }

            IEnumerable<Item> items = GetArticleItems(syndicationItem);

            article.Items = items;
            return article;
        }

        private IEnumerable<Item> GetArticleItems(SyndicationItem syndicationItem)
        {
            List<Item> items = new List<Item>();

            if (syndicationItem.Summary != null)
            {
                items.Add(new Item()
                {
                    Type = "text",
                    Value = syndicationItem.Summary.Text,
                });
            }

            if (syndicationItem.Links.Count != 0)
            {
                items.Add(new Item()
                {
                    Type = "link",
                    Value = syndicationItem.Links.FirstOrDefault().Uri.ToString(),
                });
            }

            return items;
        }
    }
}
